from django.contrib.auth.models import User
from django.contrib.auth import views as auth_views
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.views import View
from django.utils.translation import gettext_lazy as _
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_framework import viewsets, generics, views, status
from .forms import RegisterForm, ActiveAuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm


# Text to put at the end of each page's <title>.
from .models import Account, Subscribe
from .serializers import AccountSerializer, SubscribeSerializer

site_title = _('项目名🙂')

# Text to put in each page's <h1>.
site_header = _('🤗项目Demo👻')

# Text to put at the top of the admin index page.
index_title = _('不知道啥')

# URL for the "View site" link at the top of each admin page.
site_url = 'http://www.baidu.com'

# 启动导航栏，暂时不知道干嘛的
enable_nav_sidebar = True

_empty_value_display = '-'

REDIRECT_FIELD_NAME = "next"


def has_permission(request):
    # return request.user.is_active and request.user.is_staff
    return request.user.is_active  # auth 中间件添加的 user


def each_context():
    """
    Return a dictionary of variables to put in the template context for
    *every* page in the admin site.
    """
    return {
        'site_title': site_title,
        'site_header': site_header,
        'site_url': site_url,
        'is_popup': False,  # 是否取消 header
        'is_nav_sidebar_enabled': enable_nav_sidebar,
    }


class RegisterView(auth_views.FormView):
    form_class = RegisterForm
    success_url = reverse_lazy('users:password_change_done')
    template_name = 'users/register.html'
    title = _('盖亚改密码')
    extra_context = each_context()
    # register_html = "users/register.html"

    # def get(self, request):
    #     # 直接把 form 传递过去，前端甚至可以不用写各种 input 框
    #     return render(request, self.register_html)

    def post(self, request, **kwargs):
        form = RegisterForm(request.POST)
        if form.is_valid():
            # 在取值之前"必须"先检查数据是否有效
            form_data = form.cleaned_data
            username = form_data.get("username")
            password = form_data.get("password")
            # 两次密码的比较在 from 表单中已做掉
            email = form_data.get("email")
            User.objects.create_user(username=username,
                                     password=password,
                                     email=email)
            # 将页面重定向到登录页
            return redirect(reverse("users:login"))
        # from.errors 是一个 ErrorDict 类型的数据,包含出错的字段和提示信息
        # 整体和每一个错误字段内容都可以在页面格式化为 html
        return render(request, self.template_name, {"form": form, **each_context()})


class LoginView(auth_views.LoginView):
    form_class = None
    authentication_form = ActiveAuthenticationForm
    redirect_field_name = REDIRECT_FIELD_NAME  # 成功跳转的
    # template_name = "login.html"
    template_name = 'users/login.html'
    redirect_authenticated_user = False
    extra_context = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),  # next: /users/
            **(self.extra_context or each_context())
        })
        return context

    # def get(self, request, **kwargs):
    #     if has_permission(request):
    #         # Already logged-in, redirect to user index
    #         # current_app 用于反向解析时确定 namespace
    #         index_path = reverse('users:index', current_app="users")
    #         return HttpResponseRedirect(index_path)
    #     return render(request, self.template_name)
    #
    # def post(self, request, *args, **kwargs):
    #     # 使用单独方法去获取 from，只是为了让你记得去看看父类
    #     form = self.get_form()
    #     if form.is_valid():
    #         # 跳转页面的是在 get 请求中使用 next 参数指定的
    #         # next 字段是 django 默认识别的跳转页字段，可以查看父类进行修改
    #         # form_valid 中进行账号密码的验证，以及 session 信息的入库，填充等工作
    #         return self.form_valid(form)
    #     return self.form_invalid(form)
    #
    # def form_invalid(self, form):
    #     # 因为想返回错误信息，所以重写该方法
    #     # extra_context 用于添加额外返回参数 (base.ContextMixin)
    #     # 因为继承父类会使用该值，所以未重写
    #     # self.extra_context = {"form": form}  # 父类默认已经返回 form 了
    #     return super(LoginView, self).form_invalid(form)


class LogoutView(auth_views.LogoutView):
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'users/registration/logged_out.html'
    extra_context = None


class PasswordChangeView(auth_views.PasswordChangeView):
    form_class = PasswordChangeForm
    success_url = reverse_lazy('users:password_change_done')
    template_name = 'users/registration/password_change_form.html'
    title = _('盖亚改密码')


class PasswordChangeDoneView(auth_views.PasswordChangeDoneView):
    template_name = 'users/registration/password_change_done.html'
    title = _('改密码成功了')


class PasswordResetView(auth_views.PasswordResetView):
    email_template_name = 'users/registration/password_reset_email.html'  # 邮件内容模板
    extra_email_context = None
    form_class = PasswordResetForm
    from_email = None
    html_email_template_name = None
    subject_template_name = 'registration/password_reset_subject.txt'  # 邮件主题模板
    success_url = reverse_lazy('password_reset_done')
    template_name = 'users/registration/password_reset_form.html'  # 输入邮箱的页面
    title = _('开始重置密码')
    # token_generator = default_token_generator


class PasswordResetDoneView(auth_views.PasswordResetDoneView):
    template_name = 'users/registration/password_reset_done.html'
    title = _('Password reset sent')


class PasswordResetConfirmView(auth_views.PasswordResetConfirmView):
    form_class = SetPasswordForm
    post_reset_login = False
    post_reset_login_backend = None
    reset_url_token = 'set-password'
    success_url = reverse_lazy('password_reset_complete')
    template_name = 'users/registration/password_reset_confirm.html'
    title = _('Enter new password')
    # token_generator = default_token_generator


class IndexView(View):
    template_name = "users/index.html"

    def get(self, request):
        if has_permission(request):
            context = {
                'has_permission': has_permission(request),
                **each_context()
            }
            return render(request, self.template_name, context=context)
        login_path = reverse('users:login', current_app="users") + "?next=/users/"
        return HttpResponseRedirect(login_path)


class AccountViewSet(ModelViewSet):
    queryset = Account.objects.all()
    serializer_class = AccountSerializer


class SubscribeViewSet(ModelViewSet):
    queryset = Subscribe.objects.all()
    serializer_class = SubscribeSerializer


class GroupView(ReadOnlyModelViewSet):
    pass
